// 初始化数据...
items = [];
selectedItems = [];
currentSong = null;
// 加载列表项
function loadItems(filter = "") {
    const itemList = document.getElementById("item-list");
    itemList.innerHTML = "";

    // 将 filter 转换为小写
    const lowerCaseFilter = filter.toLowerCase();

    items
        .filter(item => item.toLowerCase().includes(lowerCaseFilter)) // 使用小写进行比较
        .forEach(item => {
            const listItem = document.createElement("li");
            listItem.className = "item";
            listItem.textContent = item; // 使用原始项的大小写
            listItem.onclick = () => addItem(item); // 处理点击事件
            itemList.appendChild(listItem);
        });
}


// 添加到右边的选中列表
function addItem(item) {
    if(selectedItems.length === 0 && currentSong === null){
        playSong(item);
    }
    else if (!selectedItems.includes(item) && item !== currentSong) {
        selectedItems.push(item);
        updateSelectedList();
    }
}

// 更新右边的选中列表
function updateSelectedList() {
    const selectedList = document.getElementById("selected-list");
    selectedList.innerHTML = "";
    selectedItems.forEach(item => {
        const listItem = document.createElement("li");
        listItem.className = "selected-item";
        listItem.title = item; // 设置 title 属性以显示完整歌曲名
        listItem.innerHTML = `
            <span class="song-title">${item}</span>
            <span class="remove-btn" onclick="removeItem('${item}')">&times;</span>
        `;
        selectedList.appendChild(listItem);
    });
}


// 从右边的列表中删除项
function removeItem(item) {
    const index = selectedItems.indexOf(item);
    if (index > -1) {
        selectedItems.splice(index, 1);
        updateSelectedList();
    }
}

function updateCurrentSong() {
    const currentSongElement = document.getElementById("current-song");
    currentSongElement.textContent = `当前播放： ${currentSong || "无"}`;
}

function nextSong() {
    const selectList = document.getElementById("loopSelect");
    console.log(selectList.value);
    playNextSong(false);
}

function loadMusicList() {
    const itemList = document.getElementById("item-list");
    console.log(`${contextPath}/MusicPlayer.getSongs`); // 修正为 console.log

    // 发送请求到 Servlet
    fetch(`${contextPath}/MusicPlayer.getSongs`) // 动态获取 Servlet 数据
        .then(response => {
            if (!response.ok) {
                throw new Error("网络错误，无法获取数据");
            }
            return response.json(); // 解析为 JSON
        })
        .then(songs => {
            // 将歌曲数据填入 item 数组
            items.push(...songs); // 使用扩展运算符
            loadItems(); // 在数据加载后调用 loadItems
        })
        .catch(error => console.error("获取歌曲列表失败:", error));
}

function playSong(fileName){
    console.log('播放: ' + fileName);
    const audioPlayer = document.getElementById("audioPlayer");
    audioPlayer.src = "Music/" + fileName;
    audioPlayer.play();
    currentSong = fileName;
    console.log('currentsong: '+currentSong);
    updateCurrentSong();
}

function stopSong(){
    const audioPlayer = document.getElementById("audioPlayer");
    audioPlayer.pause();
    audioPlayer.src = "";
    currentSong = null;
    updateCurrentSong();
}

function playNextSong(i){
    const selectList = document.getElementById("loopSelect");
    if(selectList.value === "Single" && currentSong !== null && i){
        playSong(currentSong);
        return;
    }
    if(selectList.value === "ListLoop"){
        if(currentSong !== null) {
            selectedItems.push(currentSong);
            playSong(selectedItems.shift());
            updateSelectedList();
            return;
        }
        return;
    }
    if(selectedItems.length !== 0){
        playSong(selectedItems.shift());
        updateSelectedList();
    }
    else{
        if(selectList.value === "Random"){
            let random = getRandomInt(0, items.length - 1);
            while(currentSong === items[random]) {
                random = getRandomInt(0, items.length - 1);
            }
            playSong(items[random]);
            return;
        }
        currentSong = null;
        stopSong();
    }
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

window.onload = function () {
    const audioPlayer = document.getElementById("audioPlayer");
    audioPlayer.volume = 0.1;
    // 搜索功能
    document.getElementById("search").addEventListener("input", function () {
        loadItems(this.value);
    });
    // 在页面加载完成后调用
    loadMusicList(); // 直接调用，不需要事件监听
}
